package com.data.modules.openapi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.Result;
import com.data.common.system.query.QueryGenerator;
import com.data.modules.openapi.entity.OpenApiApp;
import com.data.modules.openapi.entity.OpenApiAppPermission;
import com.data.modules.openapi.mapper.OpenApiAppMapper;
import com.data.modules.openapi.mapper.OpenApiAppPermissionMapper;
import com.data.modules.openapi.service.IOpenApiAppPermissionService;
import com.data.modules.openapi.service.IOpenApiAppService;
import com.data.modules.system.vo.MagicPathVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: open_api_app
 * @Author: data-boot
 * @Date:   2022-04-07
 * @Version: V1.0
 */
@Service
public class OpenApiAppServiceImpl extends ServiceImpl<OpenApiAppMapper, OpenApiApp> implements IOpenApiAppService {
    @Autowired
    OpenApiAppPermissionMapper openApiAppPermissionMapper;
    @Autowired
    OpenApiAppMapper openApiAppMapper;
    @Autowired
    private IOpenApiAppPermissionService openApiAppPermissionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editAuth(OpenApiApp openApiApp) {
        //先修改角色表
        this.updateById(openApiApp);

        //在修改权限表  先删除表中的该用户所有权限数据 再新增
        QueryWrapper<OpenApiAppPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OpenApiAppPermission::getApiId,openApiApp.getId());
        openApiAppPermissionMapper.delete(queryWrapper);

        //再新增
        String fileUrl = openApiApp.getFileUrl();
        String[] fileUrls = fileUrl.split(",");
        for (int i = 0; i < fileUrls.length; i++) {
            OpenApiAppPermission appPermission = new OpenApiAppPermission();
            appPermission.setApiId(openApiApp.getId());
            appPermission.setUrl(fileUrls[i]);
            openApiAppPermissionMapper.insert(appPermission);
        }
    }

    //public static void main(String[] args) {
    //    int[] a = {5, 7, 3, 1, 8, 9, 0, 4};
    //    int tmp = 0;
    //    boolean flag=true;
    //    for (int j = 0; j < a.length; j++) {
    //        for (int i = 0; i < a.length - 1; i++) {
    //            if (a[i] > a[i + 1]) {
    //                tmp = a[i + 1];
    //                a[i + 1] = a[i];
    //                a[i] = tmp;
    //                flag=false;
    //            }
    //        }
    //        if(flag){
    //            break;
    //        }
    //    }
    //    System.out.println(Arrays.toString(a));
    //}

    public static void main(String[] args) {
        ArrayList<String> s = new ArrayList<>();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(2);
        integers.add(9);
        integers.add(5);
        integers.add(0);
        integers.add(6);
        Collections.sort(integers);
        System.out.println(integers);
        s.add("abc");
        s.add("def");
        s.add("pdp");
        s.add("mnv");
        s.add("iuy");
        Collections.sort(s);
        System.out.println(s);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAuth(OpenApiApp openApiApp) {
        //先将角色保存
        this.save(openApiApp);
        //再保存权限都用户表
        //再新增
        String appRole = openApiApp.getAppRole();
        appRole="["+appRole+"]";
        List<MagicPathVO> magicPathVOS = JSONArray.parseArray(appRole, MagicPathVO.class);

        magicPathVOS.forEach(a->{
            OpenApiAppPermission appPermission = new OpenApiAppPermission();
            appPermission.setApiId(openApiApp.getId());
            appPermission.setApiName(a.getFilePath());
            appPermission.setMethod(a.getMethod());
            appPermission.setName(a.getFileName());
            appPermission.setUrl(a.getFileUrl());
            openApiAppPermissionMapper.insert(appPermission);

        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAuth(String id) {

        OpenApiApp openApiApp = openApiAppMapper.selectById(id);
        openApiApp.setStatus(2);
        this.updateById(openApiApp);


    }

    @Override
    public IPage<OpenApiApp> pageList(OpenApiApp openApiApp, Integer pageNo, Integer pageSize, HttpServletRequest req) {
        QueryWrapper<OpenApiApp> queryWrapper = QueryGenerator.initQueryWrapper(openApiApp, req.getParameterMap());
        Page<OpenApiApp> page = new Page<OpenApiApp>(pageNo, pageSize);
        IPage<OpenApiApp> pageList = this.page(page, queryWrapper);

        List<OpenApiAppPermission> list = openApiAppPermissionService.list();
        for (OpenApiApp apiApp : pageList.getRecords()) {
            StringBuilder stringBuilder = new StringBuilder();
            List<OpenApiAppPermission> openApiAppPermissions = list.stream().filter(a -> a.getApiId().equals(apiApp.getId())).collect(Collectors.toList());
            openApiAppPermissions.forEach(
                    a->{

                        stringBuilder.append(a.getUrl()).append(",");
                    }
            );
            if(ObjectUtil.isNotEmpty(stringBuilder)){
                String url = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                apiApp.setFileUrl(url);
            }

        }
        return pageList;
    }
}
